import axios from 'axios';

const ENCRYPT_KEY='ticketticket'

export function fetch(url,method,params={}){
    //判断obj中的投放范围、类型、状态是否为空
    let newObjs={}
    let strs=''
    for(var item in params){
        if(params[item]!=''){
            strs= "newObjs."+item+"='"+params[item]+"'";
            eval(strs);
        }
    }
    this.body = Object.assign({
        randomStr: new Date().getTime().toString(),
        reqDate: formatData('yyyyMMdd'),
        reqTime: formatData('yyyyMMddhhmmss')
    }, newObjs);
    let sing=signatureTempGenerate(this.body)
    let sha256 = require("js-sha256").sha256
    //console.log(sing)
    //console.log(sha256(sing))//这就是你加密之后的密码
    this.body.signature = sha256(sing);
    this.params=this.body
    //console.log(this.params)
    let data = method.toLocaleLowerCase() === 'get' ? 'params' : 'data';
    console.log(method,url,this.params)
    return new Promise((resolve,reject) => {
        axios({
            method,
            url,
            [data]: this.params, // 差异点在于data的值
            headers:{
                'TENANT_ID':'0',
                'Authorization':'Basic c2hyZXc6c2hyZXc='
            },
        })
        .then(response => {
            resolve(response.data);
        })
        .catch(err => {
            reject(err)
        })
    })
}
//签名
function signatureTempGenerate(data) {
    let keys = Object.keys(data).sort();
    let stringSignTemp = '';
    keys.forEach((key) => {
        if (!data[key] || key === 'password') return null;
        stringSignTemp = stringSignTemp
            ? `${stringSignTemp}&${key}=${data[key]}`
            : `${key}=${data[key]}`;
    });
    stringSignTemp = stringSignTemp
        ? `${stringSignTemp}&key=${ENCRYPT_KEY}`
        : `key=${ENCRYPT_KEY}`;
    return stringSignTemp;
}
function formatData (fmt = 'yyyy-MM-dd hh:mm:ss', date = new Date()) {
    let o = {
        "M+" : date.getMonth()+1,
        "d+" : date.getDate(),
        "h+" : date.getHours(),
        "m+" : date.getMinutes(),
        "s+" : date.getSeconds(),
        "q+" : Math.floor((date.getMonth()+3)/3),
        "S"  : date.getMilliseconds()
    };
    if(/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(let k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}